﻿/***************************************************************
 * 开发人员：网魂小兵@http://www.mozlite.com
 * 
 * 任务管理类。
 * 
 * 最后修改：2011-10-31
 * ************************************************************/
namespace Mozlite.Common
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;

    /// <summary>
    /// 任务管理类。
    /// </summary>
    public class Tasks
    {
        private Tasks() { }

        private static readonly List<TaskBase> threads = new List<TaskBase>();

        static Tasks()
        {
            Dictionary<string, DateTime> times = TaskDataProvider.Current.LoadLastExecuteTimes();
            foreach (TaskBase task in Globals.FindType<TaskBase>())
            {
                DateTime date;
                if (times.TryGetValue(task.Type, out date))
                    task.LastExecuteTime = date;
                threads.Add(task);
            }
        }
        /// <summary>
        /// 启动任务。
        /// </summary>
        public static void Start()
        {
            var thread = new System.Threading.Thread(new ThreadStart(delegate()
            {
                while (true)
                {
                    try
                    {
                        foreach (TaskBase task in threads)
                        {
                            task.Execute();
                        }
                    }
                    catch
                    {
                    }
                    System.Threading.Thread.Sleep(1000);
                }
            }));
            thread.IsBackground = true;
            thread.Start();
        }
        /// <summary>
        /// 获取程序的所有计划任务。
        /// </summary>
        public static List<TaskBase> Threads { get { return threads; } }
    }
}
